﻿using UnityEngine;
using System.Collections;

public class EnemyMoveScript2 : MonoBehaviour {
	
	NavMeshAgent agent;
	public GameObject[] moveArea;
	public int priorityAreaIndex;
	public int areaPriorityPercent;
	public GameObject moveLine;
	public bool useArea = false;
	MoveAreaScript script;
	MoveLineScript script2;
	Vector3 target = Vector3.zero;
	int lineStep = 0;
	bool openingDoor = false;
	GameObject door;
	
	// Use this for initialization
	void Start () {
		agent = (NavMeshAgent)GetComponent("NavMeshAgent");
		if (moveArea == null && useArea) {
			throw new UnityException();
		}
		if (moveLine == null && !useArea) {
			throw new UnityException();
		}
		if (!useArea) {
			script2 = (MoveLineScript)moveLine.GetComponent ("MoveLineScript");
		}
		
	}

	// Update is called once per frame
	void Update () {
		/*if (!moving) {
			if(target == Vector3.zero){
				if(useArea){
					script = (MoveAreaScript)moveArea[getRandomArea()].GetComponent ("MoveAreaScript");
					target = script.getRandomInsideArea ();
					if(script.InsidePolygon(new Vector2(target.x, target.z))){
						target.y = transform.position.y;
					}else{
						target = Vector3.zero;
					}
				}else{
					target = script2.getStep(lineStep);
				}
			}else{
				/*NavMeshPath path = new NavMeshPath();
			agent.CalculatePath(target, path);
			if (path.status != NavMeshPathStatus.PathPartial && path.status != NavMeshPathStatus.PathInvalid) {
				moving = true;
				agent.SetPath(path);
			}*/
				/*agent.destination = target;
				moving = true;
			}
		} else {
			checkDoorInPath();
			checkInTarget();
		}*/
	}
	
	void checkDoorInPath(){
		RaycastHit hit;
		Vector3 direction = transform.forward;
		Ray ray = new Ray (transform.position, direction);
		if (Physics.Raycast (ray, out hit, 1f, 1 << LayerMask.NameToLayer ("Usable"))) {
			if (hit.collider.tag == "Door") {
				if (!openingDoor) {
					door = hit.collider.gameObject;
					hit.collider.GetComponent<BaseUsableObject> ().use (gameObject);
					openingDoor = true;
				}
			} else if (hit.collider.tag == "ButtonDoor") {
				//hit.collider.GetComponent<BaseUsableObject>().use(gameObject);
			}
		} else {
			if(openingDoor){
				door.GetComponent<BaseUsableObject> ().use (gameObject);
			}
		}
	}
	
	int getRandomArea(){
		float percent = Random.value;
		if (percent > (areaPriorityPercent/100)) {
			return Random.Range(0, moveArea.Length-1);
		}else{
			return priorityAreaIndex;
		}
	}
	
	public Vector3 getMoveTarget(){
		Vector3 target = Vector3.zero;
		if (useArea) {
			while (target == Vector3.zero) {
				script = (MoveAreaScript)moveArea [getRandomArea ()].GetComponent ("MoveAreaScript");
				target = script.getRandomInsideArea ();
				if (script.InsidePolygon (new Vector2 (target.x, target.z))) {
					target.y = transform.position.y;
				} else {
					target = Vector3.zero;
				}
			}
		} else {
			target = script2.getStep(lineStep);
		}
		return target;
	}
}
